//
//  YFree.swift
//  Runner
//
//  Created by YMac on 2019/4/11.
//  Copyright © 2019 The Chromium Authors. All rights reserved.
//

import Flutter
import UIKit

class YFlutterAppDelegate:FlutterAppDelegate {
    override func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        onYConfig()
        onYCreated(application, didFinishLaunchingWithOptions: launchOptions)
        return super.application(application, didFinishLaunchingWithOptions: launchOptions)
    }
    
    func onYCreated(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) {}
    
    func onYConfig() {}
}

open class YFlutterPlugin {
     public static func register(with appDelegate:UIApplicationDelegate) {
        let navigationController = UINavigationController(rootViewController: appDelegate.window!!.rootViewController!)
        navigationController.isNavigationBarHidden = true
        appDelegate.window!!.rootViewController = navigationController
        FlutterMethodChannel(name: "YFreePlugin", binaryMessenger: navigationController.viewControllers.first as! FlutterBinaryMessenger).setMethodCallHandler { methodCall, result in
            let arguments = methodCall.arguments as? NSDictionary
            switch methodCall.method {
//             case "yLog":
//                 if let message = arguments!["message"] as? String {
//                     yFlutter.yPrint(message)
//                 } else { yFlutter.yPrint("nil") }
//             case "yDoCrash":
//                 if let commitErrorLog = YConfig.commitErrorLog {
//                     let timeFormatter = DateFormatter()
//                     timeFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
//                     let time = "异常时间：\(timeFormatter.string(from: Date()))"
//                     let device = "设备：\(YDeviceUtils.getDeviceName())_\(YDeviceUtils.getDeviceVersion())"
//                     let deviceID = "设备识别码：\(YDeviceUtils.getDeviceID())"
//                     let ipaVersion = "ipa版本号：\(YAppUtils.getAppVersionCode())_\(YAppUtils.getAppVersionName())"
//                     let exceptionMsg = "异常详情：\(arguments!["message"] as! String)"
//                     let message = "\(time)\n\(device)\n\(deviceID)\n\(ipaVersion)\n\(exceptionMsg)"
//                     yFlutter.yPrint(message)
//                     yFlutter.yPost(jkid: commitErrorLog, kv: YJsonKV().put("msg", message), callBack: { (_, _, _, _) in }, showProgress: false, showErrorToast: false)
//                 }
//             case "yRequestStorage":
//                 result(true)
//             case "yGetAppName":
//                 result(YAppUtils.getAppName())
//             case "yConfigIP":
//                 YConfig.IP = arguments!["ip"] as! String
//             case "yConfigUpdateIP":
//                 YConfig.UPDATEIP = arguments!["updateIp"] as! String
//             case "yGetDeviceID":
//                 result(YDeviceUtils.getDeviceID())
//             case "yToast":
//                 if let message = arguments!["message"] as? String {
//                     yFlutter.yToast(message)
//                 } else { yFlutter.yToast("nil") }
//             case "yPost":
//                 let kv = YJsonKV()
//                 (arguments!["jkparam"] as? NSDictionary)?.forEach { _ = kv.put($0.key as! String, "\($0.value)") }
//                 yFlutter.yPost(jkid: (arguments!["jkid"] as! String), kv: kv, callBack: { (isSuccess, results:[NSDictionary], code, message) in
//                     if isSuccess { result([ "code": "1", "results": NSString(data:try! JSONSerialization.data(withJSONObject: results, options: []) ,encoding: String.Encoding.utf8.rawValue)! , "message": nil ]) }
//                     else { result([ "code": code, "results": nil, "message": message ?? "ios yPost unSuccessed" ]) }
//                 }, showProgress: arguments!["showProgress"] as! Bool, showErrorToast: arguments!["showErrorToast"] as! Bool)
//             case "yAesEncode":
//                 result(YAESCrypt.encrypt((arguments!["content"] as! String), password: (arguments!["password"] as! String)))
//             case "yAesDecode":
//                 result(YAESCrypt.decrypt((arguments!["content"] as! String), password: (arguments!["password"] as! String)))
//             case "yIsNetAble":
//                 result(yFlutter.yIsConnectionAvailable())
//             case "yShowBuilder":
//                 let message = arguments!["message"] as! String
//                 let posTitle = arguments!["posTitle"] as! String
//                 let negTitle = arguments!["negTitle"] as! String
//                 let hasCancelCallBack = arguments!["hasCancelCallBack"] as! Bool
//                 let cancelAble = arguments!["cancelAble"] as! Bool
//                 var alertActions = [UIAlertAction]()
//                 alertActions.append(UIAlertAction(title: posTitle, style: .default) { _ in result(1) })
//                 if hasCancelCallBack { alertActions.append(UIAlertAction(title: negTitle, style: .cancel) { _ in result(0) }) }
//                 yFlutter.yShowAlertController(alertView: UIAlertController(title: nil, message: message, preferredStyle: .alert), hasCancelAction: cancelAble, alertActions: alertActions)
//             case "yShowActionSheet":
//                 let message = arguments!["message"] as! String
//                 let actions = arguments!["actions"] as! [String]
//                 var alertActions = [UIAlertAction]()
//                 actions.enumerated().forEach { i, action in
//                     let index = i
//                     alertActions.append(UIAlertAction(title: action, style: .default) {
//                         result(["index" : index , "action" : $0.title!])
//                     })
//                 }
//                 yFlutter.yShowAlertController(alertView: UIAlertController(title: nil, message: message, preferredStyle: UI_USER_INTERFACE_IDIOM() == .pad ? .alert : .actionSheet), hasCancelAction: true, alertActions: alertActions)
//             case "yShowSelectBuilder":
//                 let message = arguments!["message"] as! String
//                 let actions = arguments!["actions"] as! [String]
//                 let cancelAble = arguments!["cancelAble"] as! Bool
//                 var alertActions = [UIAlertAction]()
//                 actions.enumerated().forEach { i, action in
//                     let index = i
//                     alertActions.append(UIAlertAction(title: action, style: .default) {
//                         result(["index" : index , "action" : $0.title!])
//                     })
//                 }
//                 if cancelAble { alertActions.append(UIAlertAction(title: "取消", style: .cancel) { _ in result(nil) }) }
//                 yFlutter.yShowAlertController(alertView: UIAlertController(title: nil, message: message, preferredStyle: .alert), hasCancelAction: false, alertActions: alertActions)
//             case "yRunOnUIThread":
//                 _ = yFlutter.yRunOnUIThreadDelay(delay: (arguments!["delay"] as! TimeInterval) / 1000.0) { result(nil) }
//             case "yCheckUpdate":
//                 YUpdateUtils.checkUpdate(vc: yFlutter)
//             case "yFinishApplication":
//                 exit(0)
//             case "yBase64Encode":
//                 result((arguments!["content"] as! String).data(using: .utf8)?.base64EncodedData())
//             case "yBase64Decode":
//                 result(String(data: Data(base64Encoded: arguments!["content"] as! String)!, encoding: .utf8)!)
//             case "ySave":
//                 UserDefaults.standard.set(arguments!["value"] as! String, forKey: arguments!["key"] as! String)
//                 UserDefaults.standard.synchronize()
//             case "yRead":
//                 result(UserDefaults.standard.string(forKey: arguments!["key"] as! String))
//             case "yDelete":
//                 UserDefaults.standard.removeObject(forKey: arguments!["key"] as! String)
//                 UserDefaults.standard.synchronize()
//             case "yRegisterBroadcast":
//                 let broadcastName = arguments!["broadcastName"] as! String
//                 yFlutter.yRegisterReceiver(broadcastName) { notification in
//                     yRunFlutter(className: arguments!["pageName"] as! String, methodName: "onYReceiveBroadcast", params: [
//                         "broadcastName" : broadcastName,
//                         "broadcastParams" : notification.userInfo == nil ? nil : notification.userInfo!["broadcastParams"]
//                     ])
//                 }
//             case "ySendBroadcast":
//                 let broadcastName = arguments!["broadcastName"] as! String
//                 if let broadcastParams = arguments!["broadcastParams"] as? [String : Any] {
//                     yFlutter.ySendBroadcast(broadcastName, ["broadcastParams":broadcastParams])
//                 } else { yFlutter.ySendBroadcast(broadcastName) }
//             case "yUnregisterReceiver":
//                 yFlutter.yUnRegisterReceiver(arguments!["broadcastName"] as! String)
//             case "yShowProgress":
//                 yFlutter.yShowLoadingProgress()
//             case "yDismissProgress":
//                 yFlutter.yDismissLoadingProgress()
//             case "yCopyClipBoard":
//                 UIPasteboard.general.string = arguments!["content"] as! String
            default: result(FlutterMethodNotImplemented)
            }
        }
    }
    
    public static func yRunFlutter(className: String, methodName: String, params: [String: Any]? = nil, callBack: ((Any) -> ())? = nil) {
        let appDelegate = UIApplication.shared.delegate as! UIApplicationDelegate
        let navigationController = UINavigationController(rootViewController: appDelegate.window!!.rootViewController!)
        FlutterMethodChannel(name: className, binaryMessenger: (navigationController.viewControllers.first) as! FlutterBinaryMessenger).invokeMethod(methodName, arguments: params) { (result) in
            if result != nil { callBack?(result!) }
        }
    }
}
